<template>

  <div class="charge-pileactive" ref="pileactive_ref"></div>

</template>

<script>
export default {
  data() {
    return {
      chartInstance: null,
      allData: null,
      currentIndex: 0, // 当前显示的数据
      timerId: null, // 定时器的标识
      working: 0, //正在工作的充电桩
      free: 0, //空闲的充电桩
      error: 0, //故障的充电桩
    };
  },
  mounted() {
    this.initChart();
    this.getData();
  },
  destroyed() {
    clearInterval(this.timerId);
  },
  methods: {
    initChart() {
      this.chartInstance = this.$echarts.init(
        this.$refs.pileactive_ref,
        "chalk"
      );
      //切换主题用的
      //   this.chartInstance = this.$echarts.init(
      //     this.$refs.pileactive_ref,
      //     "vintage"
      //   );

      const initOption = {
        title: {
          text: "▎充电桩状态",
          left: 20,
          top: 20,
        },
      };
      this.chartInstance.setOption(initOption);
      this.chartInstance.on("mouseover", () => {
        clearInterval(this.timerId);
      });
      this.chartInstance.on("mouseout", () => {
        this.startInterval();
      });
    },
    async getData() {
      // 获取服务器的数据, 对this.allData进行赋值之后, 调用updateChart方法更新图表
      const res = await this.$axios.get("pile/admin/monitor");
      this.allData = res;
      this.updateChart();
      this.startInterval();
    },
    updateChart() {
      // 处理图表需要的数据
      this.allData.map((item) => {
        if (item.error) return this.error++;
        if (item.active) return this.working++;
        return this.free++;
      });
      const dataOption = {
        legend: {
          orient: "vertical",
          left: "right",
          data: ["工作中", "空闲", "故障"],
        },
        tooltip: {
          trigger: "item",
          formatter: "{b} : {c} ({d}%)",
        },
        series: {
          type: "pie",
          data: [
            {
              name: "工作中",
              value: this.working,
            },
            {
              name: "空闲",
              value: this.free,
            },
            {
              name: "故障",
              value: this.error,
            },
          ],
        },
      };
      this.chartInstance.setOption(dataOption);
    },

    startInterval() {
      if (this.timerId) {
        clearInterval(this.timerId);
      }
      this.timerId = setInterval(() => {
        this.currentIndex++;
        if (this.currentIndex > 1) {
          this.currentIndex = 0;
        }
        this.updateChart(); // 在更改完currentIndex之后 , 需要更新界面
      }, 5000);
    },
  },
};
</script>

<style lang="less" scoped>
.charge-pileactive {
  width: 500px;
  height: 400px;
  overflow: hidden;
  border-radius: 20px !important;
}
</style>
